from typing import Dict, Any
from langgraph.graph import StateGraph
from pydantic import BaseModel, Field
from intelli_port.data_layer.clients import mysql_execute_write, mysql_transaction


class ServiceAssistance(BaseModel):
    type: str = Field(default="special_assistance")
    accepted: bool
    request_id: int | None = None


def build_assistance_subgraph():
    g = StateGraph(dict)

    def create_request(state: Dict[str, Any]) -> Dict[str, Any]:
        slots = state.get("slots") or {}
        assist_type = str(slots.get("assistance_type") or "wheelchair")
        ok = False
        rid = None
        try:
            with mysql_transaction() as cur:
                cur.execute(
                    "INSERT INTO service_requests(passenger_id, service_type, priority, status, robot_id, location, created_at) VALUES(NULL,%s,%s,%s,NULL,NULL,NOW())",
                    (assist_type, 8, "pending"),
                )
                cur.execute("SELECT LAST_INSERT_ID()")
                r = cur.fetchone()
                if r and r[0] is not None:
                    rid = int(r[0])
                ok = True
        except Exception:
            ok = False
        svc = ServiceAssistance(accepted=ok, request_id=rid).model_dump()
        return {**state, "service": svc}

    g.add_node("assistance", create_request)
    g.set_entry_point("assistance")
    return g.compile()